define(['admin/routes', 'loader', 'angularAMD', 'bootstrap', 'ui-bootstrap', 'angular-loading-bar', 'w5c.validator',
'ui.select', 'angular-sanitize', 'blockUI', 'ui.route', 'notify', 'ng-Storage', 'angular-city-select', //'ui.file.manage',
'bootstrap-datetimepicker-zh', 'ng-clip', 'bootstrap-colorpicker'], function (config, loader, angularAMD) {
    "use strict";

    var app = angular.module("webapp", ['ngSanitize', 'ui.bootstrap', 'ui.router', 'ui.select', 'ngStorage',
        'angular-loading-bar', 'w5c.validator', 'angular.city.select'/*, 'ui.file.manage', 'ngClipboard'*/]);

    app.config(["w5cValidatorProvider", function (w5cValidatorProvider) {
        w5cValidatorProvider.config({ blurTrig: true, showError: true, removeError: true });
    }]);

    //app.config(['ngClipProvider', function (ngClipProvider) {
    //    ngClipProvider.setPath("/scripts/lib/zeroclipboard/ZeroClipboard.swf");
    //}]);

    app.config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) {
        // 配置路由
        if (config.routes != undefined) {
            angular.forEach(config.routes, function (route, path) {
                if (route.template)
                    $stateProvider.state(path, angularAMD.route({
                        template: route.template,
                        url: route.url,
                        resolve: loader(route.dependencies)
                    }));
                else
                    $stateProvider.state(path, angularAMD.route({
                        templateUrl: route.templateUrl,
                        url: route.url,
                        resolve: loader(route.dependencies)
                        //, allowAnonymous: route.allowAnonymous
                    }));
            });
        }
        // 默认路由
        if (config.defaultRoute != undefined) {
            $urlRouterProvider.when("", config.defaultRoute);
        }
        $httpProvider.interceptors.push(['$rootScope', '$q', '$location', '$timeout', function ($rootScope, $q, $location, $timeout) {
            return {
                'request': function (config) {
                    //处理AJAX请求（否则后台IsAjaxRequest()始终false）
                    config.headers['X-Requested-With'] = 'XMLHttpRequest';
                    return config || $q.when(config);
                },
                'requestError': function (rejection) {
                    return rejection;
                },
                'response': function (response) {
                	if(response.data.result_code === 401 || response.data.result_code === 403)
                        $timeout(function () { $location.path('/login'); }, 3000);
                    return response || $q.when(response);
                },
                'responseError': function (response) {
                    if (response.status === 401 || response.status === 403)
                        $timeout(function () { $location.path('/login'); }, 3000);
                    return $q.reject(response);
                }
            };
        }]);
    });

    app.config(function ($controllerProvider, $compileProvider, $filterProvider, $provide, $injector) {
        // 在这里定义一个新的全局方法, 方便进行第三方模块的加载
        window.Library = (function () {

            var providers = {
                '$controllerProvider': $controllerProvider,
                '$compileProvider': $compileProvider,
                '$filterProvider': $filterProvider,
                '$provide': $provide
            };

            var cache = {};

            return function Library(module) {

                // already activated
                if (cache[module]) {
                    return;
                }

                var module = angular.module(module);

                var i;

                if (module.requires) {
                    for (i = 0; i < module.requires.length; i++) {
                        Library(module.requires[i]);
                    }
                }

                var invokeArgs, provider, method, args;
                for (i = 0; i < module._invokeQueue.length; i++) {
                    invokeArgs = module._invokeQueue[i];
                    provider = providers[invokeArgs[0]];
                    method = invokeArgs[1];
                    args = invokeArgs[2];
                    provider[method].apply(provider, args);
                }

                for (i = 0; i < module._configBlocks.length; i++) {
                    $injector.invoke(module._configBlocks[i]);
                }

                for (i = 0; i < module._runBlocks.length; i++) {
                    $injector.invoke(module._runBlocks[i]);
                }

                cache[module] = true;
            };
        });
    });

    app.run(function ($rootScope, $location, $http) {
        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            if ($rootScope.is_login) {
                _restrictedPage($rootScope.currentUser);
            }
            else {
                $http({ method: 'get', url: '/common/site' }).success(function (response) {
                    if (!response.data) return;
                    $rootScope.is_login = true;
                    $rootScope.site = response.data.site;
                    $rootScope.siteImg = response.data.site.img_url;
                    $rootScope.currentUser = response.data.currentUser;
                    _restrictedPage($rootScope.currentUser);
                 });
            //$http({ method: 'get', url: '/common/img' }).success(function (response) {
            //    if (response.result_code == 1000)
            //        $rootScope.siteImg = response.data;
            //});
            }
        });
        function _restrictedPage(currentUser) {
            var restrictedPage = $.inArray($location.path(), ['/login']) === -1;
            if (restrictedPage && !currentUser) {
                $location.path('/login');
            } 
        }
    });

    app.directive("btnLoading", function () {
        return {
            restrict: "A",
            scope: { loadingText: "@", btnLoading: "=", ifDisabled: "=?" },
            link: function (t, e) {
                var i = e.html();
                t.$watch("btnLoading", function (a) {
                    angular.isUndefined(a) || (t.ifDisabled = angular.isUndefined(t.ifDisabled) ? !0 : t.ifDisabled, t.ifDisabled && e.prop("disabled", a), t.loadingText = "@" == t.loadingText ? '<i class="fa fa-spinner fa-spin"></i>' : t.loadingText, e.html(a ? t.loadingText || "loading..." : i))
                })
            }
        }
    });

    app.directive('datetime', function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            scope: {
                select: '&'
            },
            link: function (scope, element, attrs, ngModel) {
                var optionsObj = { todayBtn: 1, autoclose: 1, language: 'zh-CN' ,todayHighlight: 1, startView: 2, forceParse: 0, showMeridian: 1, format: 'yyyy-mm-dd hh:ii'};
                element.datetimepicker(optionsObj);
            }
        };
    });

    app.directive('date', function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            scope: {
                select: '&'
            },
            link: function (scope, element, attrs, ngModel) {
                var optionsObj = { todayBtn: 1, autoclose: 1, language: 'zh-CN' ,todayHighlight: 1, startView: 2, minView: 2, forceParse: 0, format: 'yyyy-mm-dd'};
                element.datetimepicker(optionsObj);
            }
        };
    });

    app.directive('time', function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            scope: {
                select: '&'
            },
            link: function (scope, element, attrs, ngModel) {
                var optionsObj = { todayBtn: 1, autoclose: 1, language: 'zh-CN' ,todayHighlight: 1, startView: 1, minView: 0, maxView: 1, forceParse: 0, format: "hh:ii"};
                element.datetimepicker(optionsObj);
            }
        };
    });

    app.directive('colorpicker', function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            scope: {
                select: '&'
            },
            link: function (scope, element, attrs, ngModel) {
                if (!ngModel) return;
                var updateModel = function (dateTxt) {
                    scope.$apply(function () {
                        ngModel.$setViewValue(dateTxt);
                    });
                };

                element.colorpicker().on('changeColor', function (ev) {
                    updateModel(ev.color.toHex());
                });
            }
        };
    });

    app.filter('propsFilter', function () {
        return function (items, props) {
            var out = [];
            if (angular.isArray(items)) {
                var keys = Object.keys(props);
                items.forEach(function (item) {
                    var itemMatches = false;
                    for (var i = 0; i < keys.length; i++) {
                        var prop = keys[i];
                        var text = props[prop].toLowerCase();
                        if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
                            itemMatches = true;
                            break;
                        }
                    }
                    if (itemMatches) {
                        out.push(item);
                    }
                });
            } else {
                out = items;
            }
            return out;
        };
    });

    app.filter('thumbnail', function () {
        return function (img_src, w, h, img_url) {
            if (img_src == undefined) return;
            return (img_url ? img_url : "") + img_src+'?x-oss-process=image/resize,m_fixed,w_'+w+',h_'+h+'';
        }
    });

    app.filter('channel_name', function () {
        return function (channel) {
            if(channel==1)return "恒丰";
        	else if(channel==2)return "林聪";
        	else if(channel==3)return "汇享";
        	else if(channel==4) return "卡友";
        	else if(channel==5) return "商付宝聚合";
        	else if(channel==6) return "睿付快捷";
        	else if(channel==7) return "传话";
        	else if(channel==8) return "睿付代还";
        	else if(channel==9) return "汇享2";
        	else if(channel==10) return "睿付快捷2";
        	else if(channel==11) return "xsft";
        	else if(channel==12) return "睿付4511";
        	else if(channel==13) return "unipay无积分";
        	else if(channel==14) return "score通用积分";
        	else if(channel==15) return "rpayBh百货";
        	else if(channel==16) return "开联通支付";
        	else if(channel==17) return "top封顶支付";
        	else if(channel==18) return "首信易支付";
        	else if(channel==19) return "景区支付";
        	else if(channel==20) return "商旅支付";
        	else if(channel==21) return "百货支付";
        	else if(channel==23) return "slscore支付";
        	else if(channel==25) return "ltd支付";
        }
    });

    app.factory("utils", function ($uibModal) {
        var methods = {
            confirm: function (data) {
                return $uibModal.open({
                    templateUrl: '/tpl/confirmModal.html',
                    backdrop: "static",
                    controller: "confirmModal",
                    resolve: {
                        items: function () {
                            return data;
                        }
                    }
                });
            },
            notify: function (content, type) {
                $.notify(content, { type: type, delay: 1000, z_index: 1000000, placement: { from: 'top', align: 'right' } });
            },
            warning: function (content) {
                methods.notify(content, "warning");
            },
            success: function (content) {
                methods.notify(content, "success");
            },
            error: function (content) {
                methods.notify(content, "danger");
            },
            remove: function (list, item, fn) {
                angular.forEach(list, function (i, v) {
                    if (fn ? (fn(i, item)) : (i.$$hashKey === item.$$hashKey)) {
                        list.splice(v, 1);
                        return false;
                    }
                    return true;
                });
            },
            inArray: function (val, array, fn) {
                var has = false;
                angular.forEach(array, function (v) {
                    if (fn && fn(val, v) || val === v) {
                        has = true;
                        return false;
                    }
                    return true;
                });
                return has;
            }
        }
        return methods;
    });

    app.directive('sendsms', function ($http, $interval, utils) {
        return {
            restrict: 'AC',
            link: function (scope, element, attrs, ngModel) {
                var ele = element[0];
                var use_type = attrs.sendsms;
                var countdown = Number.parseInt(attrs.countdown || 60);

                scope.send_sms_code = false;

                var btn = $('button', ele);
                btn.html("获取验证码");
                btn.click(function () {
                    var mobile = scope.$eval(attrs.mobile);
                    if (!mobile || (!/^(13[0-9]|14[0-9]|15[0-9]|18[0-9])\d{8}$/i.test(mobile))) {
                        utils.error('请填写手机号码获取验证码');
                        return false;
                    }
                    btn.html("发送中...");
                    $http({ method: 'post', url: '/common/regsms', data: { mobile: mobile, use_type: use_type } }).success(function (response) {
                        if (response.result_code == 1000) {
                            times();
                            utils.success('请查收验证码');
                        } else utils.error('获取验证码失败');
                    });
                });

                function times() {
                    var second = countdown, timePromise = undefined;
                    timePromise = $interval(function () {
                        if (second <= 0) {
                            $interval.cancel(timePromise);
                            timePromise = undefined;

                            second = countdown;
                            scope.send_sms_code = false;
                            btn.html("重发验证码");
                        } else {
                            scope.send_sms_code = true;
                            btn.html(second + "s后失效");
                            second--;
                        }
                    }, 1000, 100);
                }
            }
        };
    });

    app.controller("confirmModal", ['$scope', '$uibModalInstance', 'items', function ($scope, $uibModalInstance, items) {
        var methods = {
            ok: function () {
                $uibModalInstance.close(true);
            },
            cancel: function () {
                $uibModalInstance.dismiss('cancel');
            },
            text: items
        };
        $.extend($scope, methods);
    }]);

    app.controller("errorModal", ['$scope', '$uibModalInstance', 'error', function ($scope, $uibModalInstance, error) {
        var methods = {
            cancel: function () {
                $uibModalInstance.dismiss('cancel');
            },
            report: function () {
                if (error.status == 401)
                	$location.path('/login');
                else
                    $uibModalInstance.close(true);
            },
            error: error
        }
        angular.extend($scope, methods);
    }]);

    app.filter('toHtml', ['$sce', function ($sce) {
        return function (text) {
            return $sce.trustAsHtml(text);
        };
    }]);

    return angularAMD.bootstrap(app);
});